import 'package:aitao_flutter/common_ui/age_widget.dart';
import 'package:aitao_flutter/common_ui/circle_avatar.dart';
import 'package:aitao_flutter/res/r.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/text_style.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../common_ui/empty_view.dart';
import '../common_ui/photo_view.dart';
import '../model/dynamic_model.dart';
import '../refresh/custom_refresh_footer.dart';
import '../refresh/custom_refresh_header.dart';
import '../request/api.dart';
import '../request/requestManager.dart';
import '../routes/routes.dart';
import '../utils/alert_utils.dart';

class MineDynamicPage extends StatefulWidget {
  const MineDynamicPage({super.key});

  @override
  State<MineDynamicPage> createState() => _MineDynamicPageState();
}

class _MineDynamicPageState extends State<MineDynamicPage>
    with AutomaticKeepAliveClientMixin {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final List<DynamicModel> _list = [];
  int _page = 1;
  int _totalPage = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _list.isEmpty
        ? EmptyView()
        : SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: _page < _totalPage,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            header: CustomClassicHeader(),
            footer: const CustomClassicFooter(),
            child: ListView.builder(
              itemBuilder: ((context, index) {
                return dynamicItem(index);
              }),
              itemCount: _list.length,
            ),
          );
  }

  Widget dynamicItem(int index) {
    DynamicModel model = _list[index];
    return Container(
      color: ColorStyle.whiteColor,
      padding: EdgeInsetsStyle.edgeInsets(14, 22),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.max,
            children: [
              GestureDetector(
                child: CircleAvatarWidget(
                  url: model.avatar ?? '',
                  gender: model.gender ?? 1,
                  imgWidth: 50,
                  imgHeight: 50,
                ),
                onTap: () {
                  Get.toNamed(Routes.personalPage,
                      parameters: {'userId': model.userId.toString()});
                },
              ),
              Box.hBox10,
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      GestureDetector(
                        child: Text(
                          model.nickname ?? '',
                          style: Styles.mainText_15,
                        ),
                        onTap: () {
                          Get.toNamed(Routes.personalPage,
                              parameters: {'userId': model.userId.toString()});
                        },
                      ),
                      Box.hBox5,
                      AgeWidget(
                        age: model.age ?? 18,
                        gender: model.gender ?? 1,
                      ),
                      const Spacer(),
                      Align(
                          alignment: Alignment.centerRight,
                          child: GestureDetector(
                            child: const Icon(
                              Icons.more_horiz_sharp,
                              color: ColorStyle.aaaaaaColor,
                            ),
                            onTap: () {
                              focusClick(model, index);
                            },
                          ))
                    ],
                  ),
                  Box.vBox5,
                  Text(
                    model.dateline ?? '',
                    style: Styles.greyText_13,
                  )
                ],
              )),
            ],
          ),
          Box.vBox10,
          Text(
            model.content ?? '',
            style: const TextStyle(
                fontSize: 15, color: ColorStyle.normalTextColor),
          ),
          Box.vBox10,
          dynamicImgContainer(model),
          Box.vBox10,
          dynamicBottomContainer(model, index)
        ],
      ),
    );
  }

  Widget dynamicImgContainer(DynamicModel model) {
    if (model.images == null) {
      return Container();
    }
    if (model.images!.length == 1) {
      double imgWidth = 0.0;
      double imgHeight = 0.0;

      DynamicImage image = model.images!.first;
      if (image.width! >= image.height!) {
        imgWidth = MediaQuery.of(context).size.width * 0.55;
        imgHeight = image.height! * imgWidth / image.width!;
      } else {
        imgHeight = MediaQuery.of(context).size.width * 0.55;
        imgWidth = image.width! * imgHeight / image.height!;
      }
      return GestureDetector(
          child: Container(
            color: ColorStyle.whiteColor,
            width: imgWidth,
            height: imgHeight,
            child: CachedNetworkImage(
                imageUrl: SpUtil.getImageUrl(image.url ?? '')),
          ),
          onTap: () {
            List<String> imageList = model.images!.map((e) {
              String imgUrl = SpUtil.getImageUrl(e.url ?? '');
              return imgUrl;
            }).toList();
            Navigator.push(
              context,
              PageRouteBuilder(
                pageBuilder: (context, animation, secondaryAnimation) {
                  return FadeTransition(
                    opacity: animation,
                    child: PhotoViewPage(
                      imageList: imageList,
                      index: 0,
                    ),
                  );
                },
              ),
            );
          });
    } else {
      return GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            childAspectRatio: 1.1,
            mainAxisSpacing: 12,
            crossAxisSpacing: 18,
            crossAxisCount: 3),
        itemBuilder: (context, index) {
          return GestureDetector(
            child: Container(
              color: ColorStyle.whiteColor,
              child: CachedNetworkImage(
                imageUrl: SpUtil.getImageUrl(model.images?[index].url ?? ''),
                fit: BoxFit.fitWidth,
              ),
            ),
            onTap: () {
              List<String> imageList = model.images!.map((e) {
                String imgUrl = SpUtil.getImageUrl(e.url ?? '');
                return imgUrl;
              }).toList();
              Navigator.push(
                context,
                PageRouteBuilder(
                  pageBuilder: (context, animation, secondaryAnimation) {
                    return FadeTransition(
                      opacity: animation,
                      child: PhotoViewPage(
                        imageList: imageList,
                        index: index,
                      ),
                    );
                  },
                ),
              );
            },
          );
        },
        itemCount: model.images?.length,
      );
    }
  }

  Widget dynamicBottomContainer(DynamicModel model, int index) {
    return Row(children: [
      Expanded(
          child: dynamicLikesWidget(
        model.likers ?? [],
      )),
      GestureDetector(
        child: Image.asset(model.isLike == 0
            ? ImagePath.assetsDynamicLikeNormal
            : ImagePath.assetsDynamicLikeSelect),
        onTap: () {
          likeBtnClick(model.id ?? 0, model.isLike == 0 ? 1 : 0, index);
        },
      ),
      Box.hBox10,
      Image.asset(ImagePath.assetsDynamicChat),
    ]);
  }

  Widget dynamicLikesWidget(List<DynamicLiker> list) {
    if (list.isEmpty) {
      return Container();
    }
    List<DynamicLiker> tempList = [];
    for (var i = 0; i < list.length; i++) {
      if (i == 3) break;
      tempList.add(list[i]);
    }
    return Container(
        color: ColorStyle.whiteColor,
        width: 200,
        height: 50,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
                margin: EdgeInsetsStyle.only(top: 5, right: 5),
                width: 28 + tempList.length * 14,
                color: ColorStyle.whiteColor,
                child: Stack(
                  alignment: Alignment.bottomLeft,
                  children: tempList.asMap().entries.map((e) {
                    return Positioned(
                        top: 0,
                        left: double.parse((20 * e.key).toString()),
                        child: CircleAvatarWidget(
                            url: e.value.avatar ?? '',
                            gender: e.value.gender ?? 1,
                            imgHeight: 28,
                            imgWidth: 28));
                  }).toList(),
                )),
            Expanded(
                child: Text(
              '等${list.length}人觉得很棒',
              style: Styles.greyText_12,
            ))
          ],
        ));
  }

  @override
  void initState() {
    super.initState();
    loadNewList();
  }

  void loadNewList() async {
    var result = await RequestManager()
        .post(API.getDynamicList, params: {'page': _page, 'type': 3});
    if (result != null && result['code'] == 0) {
      _list.clear();
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      List tempList = result['data']['list'];
      for (var element in tempList) {
        DynamicModel m = DynamicModel.fromJson(element);
        // m.showAllText = m.content
        _list.add(m);
      }
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.getDynamicList, params: {'type': 3, 'page': _page});
    if (result != null && result['code'] == 0) {
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      List tempList = result['data']['list'];
      _list.addAll(tempList.map((e) {
        DynamicModel m = DynamicModel.fromJson(e);
        return m;
      }));
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _onRefresh() {
    _page = 1;
    _totalPage = 1;
    loadNewList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _page += 1;
    loadMoreList();
    _refreshController.loadComplete();
  }

  /// 动态点赞: 0-点赞  1-取消点赞
  void likeBtnClick(int dynamicId, int type, int index) async {
    if (dynamicId == 0) return;
    var result = await RequestManager()
        .post(API.dynamicLike, params: {'dynamic_id': dynamicId, 'type': type});
    if (result != null && result['code'] == 0) {
      // 本地处理点赞结果
      int likeCount = result['data']['like_count'];
      int isLike = result['data']['is_like'];
      List tempList = result['data']['likers'];
      List<DynamicLiker> likers = tempList.map((e) {
        return DynamicLiker.fromJson(e);
      }).toList();
      setState(() {
        _list[index].isLike = isLike;
        _list[index].likeCount = likeCount;
        _list[index].likers = likers;
      });
    }
  }

  /// 关注
  void focusClick(DynamicModel model, int index) async {
    List<String> actions = [];
    if (model.userId == SpUtil.getUserData().userinfo?.userId) {
      actions.add('删除');
    } else {
      actions.add(model.isFollow == 1 ? '取消关注' : '关注');
      actions.add('举报');
    }
    AlertUtils().showBottomListAlert(Get.context!, (e) async {
      if (e == '举报') {
        Get.toNamed(Routes.reportPage, parameters: {
          'type': '1',
          'reportUid': (model.userId ?? 0).toString()
        });
      }
      if (e == '关注' || e == '取消关注') {
        var result = await RequestManager()
            .post(API.followUser, params: {'follow_uid': model.userId});
        if (result != null && result['code'] == 0) {
          // 本地处理关注结果
          setState(() {
            _list[index].isFollow = result['message'] == '取消关注成功' ? 0 : 1;
          });
        }
      }
    }, '', actions);
  }
}
